import { Modal, message, Form, Input, Button, Select } from "antd";
import { useState } from "react";
import React from "react";
import { CloseOutlined } from "@ant-design/icons";
import { userApi } from "../../api/services/user/user";
import type { SendCodeRequest, FinalizeRegisterRequest, ApiResponse, RegisterResponse } from "../../api/dto/user";
import { useUser } from "../../hooks/useUser";

import "../../styles/globals.css";
import "./register.less";

interface RegisterProps {
  open: boolean;
  onClose: () => void;
  onLoginClick: () => void;
}

interface RegisterFormValues {
  email: string;
  code: string;
  profileId: string;
  name: string;
  phoneNumber: string;
  passwordHash: string;
  passwordConfirmation: string;
  systemRole: number;
}

const Register: React.FC<RegisterProps> = ({ open, onClose, onLoginClick }) => {
  const [form] = Form.useForm<RegisterFormValues>();
  const [sendingCode, setSendingCode] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const [registering, setRegistering] = useState(false);
  const { login } = useUser();

  const isSuccessResponse = (code: number | string | undefined): boolean => {
    if (code === undefined) return false;
    return [0, 200, "0", "200"].includes(code as number | string);
  };

  const getErrorMessage = (response: ApiResponse<unknown> | RegisterResponse, defaultMessage: string): string => {
    return response.message || response.msg || defaultMessage;
  };

  const handleSendCode = async () => {
    try {
      const values = await form.validateFields([
        'email',
        'profileId',
        'name',
        'phoneNumber',
        'passwordHash',
        'passwordConfirmation',
        'systemRole'
      ]);

      if (values.passwordHash !== values.passwordConfirmation) {
        message.error("两次输入的密码不一致");
        return;
      }

      const requestData: SendCodeRequest = {
        email: values.email,
        scene: 1,
        name: values.name,
        profileId: values.profileId,
        phoneNumber: values.phoneNumber,
        passwordHash: values.passwordHash,
        passwordConfirmation: values.passwordConfirmation,
        systemRole: values.systemRole,
      };

      console.log('发送验证码请求数据:', requestData);
      setSendingCode(true);
      const response = await userApi.sendCode(requestData);
      console.log('验证码发送响应:', response);

      if (isSuccessResponse(response.code)) {
        message.success("验证码已发送，请查收邮箱");
        setCountdown(60);
        const timer = setInterval(() => {
          setCountdown((prev) => {
            if (prev <= 1) {
              clearInterval(timer);
              return 0;
            }
            return prev - 1;
          });
        }, 1000);
      } else {
        message.error(getErrorMessage(response, "发送验证码失败"));
      }
    } catch (error) {
      console.error("发送验证码出错:", error);
      message.error("请填写必要的信息后再获取验证码");
    } finally {
      setSendingCode(false);
    }
  };

  const handleFinish = async (values: RegisterFormValues) => {
    if (!values.code) {
      message.error("请输入验证码");
      return;
    }

    try {
      setRegistering(true);
      const finalizeData: FinalizeRegisterRequest = {
        email: values.email,
        code: values.code,
        scene: 1,
      };

      const response = await userApi.finalizeRegister(finalizeData);
      console.log('完成注册响应:', response);

      if (isSuccessResponse(response.code)) {
        message.success("注册成功！");
        if (response.data?.token) {
          localStorage.setItem("token", response.data.token);
          if (response.data.userInfo) {
            localStorage.setItem("userInfo", JSON.stringify(response.data.userInfo));
            // 更新全局用户状态
            login(response.data.userInfo);
          }
        }
        onClose();
      } else {
        message.error(getErrorMessage(response, "注册失败，请重试"));
      }
    } catch (error) {
      console.error("注册出错:", error);
      message.error("注册失败，请稍后再试");
    } finally {
      setRegistering(false);
    }
  };

  return (
    <Modal
      open={open}
      onCancel={onClose}
      footer={null}
      closable={false}
      width={550}
      style={{ top: 20 }}
      maskClosable={false}
      className="register-modal"
    >
      <div className="register-container">
        <div className="register-header">
                <img
                  src="https://makabaka7-x.github.io/Swust_UI_New/images/logo.png"
                  alt="Logo"
                />
          <h2>注册账号</h2>
          <CloseOutlined
            onClick={onClose}
            className="close-button"
          />
              </div>

        <div className="register-form">
          <Form<RegisterFormValues>
            form={form}
            layout="vertical"
            onFinish={handleFinish}
            requiredMark={false}
            size="middle"
          >
            <Form.Item
              label="学号"
              name="profileId"
              rules={[{ required: true, message: "请输入学号" }]}
            >
              <Input placeholder="请输入学号" />
            </Form.Item>

            <Form.Item
              label="姓名"
              name="name"
              rules={[{ required: true, message: "请输入姓名" }]}
            >
              <Input placeholder="请输入姓名" />
            </Form.Item>

            <Form.Item
              label="手机号"
              name="phoneNumber"
              rules={[{ required: true, message: "请输入手机号" }]}
            >
              <Input placeholder="请输入手机号" />
            </Form.Item>

            <Form.Item
              label="角色"
              name="systemRole"
              initialValue={1}
            >
              <Select>
                <Select.Option value={1}>学生</Select.Option>
                <Select.Option value={2}>教师</Select.Option>
              </Select>
            </Form.Item>

            <Form.Item
              label="邮箱"
              name="email"
              rules={[
                { required: true, message: "请输入邮箱" },
                { type: "email", message: "请输入有效的邮箱地址" }
              ]}
            >
              <Input placeholder="请输入邮箱" />
            </Form.Item>

            <Form.Item label="验证码">
              <div style={{ display: "flex", gap: "15px" }}>
                <Form.Item
                  name="code"
                  noStyle
                  rules={[{ required: true, message: "请输入验证码" }]}
                >
                  <Input placeholder="请输入验证码" style={{ flex: 1 }} />
                </Form.Item>
                <Button
                  type="primary"
                  onClick={handleSendCode}
                  disabled={sendingCode || countdown > 0}
                  className="verification-btn"
                >
                  {countdown > 0 ? `${countdown}秒` : sendingCode ? "发送中..." : "获取验证码"}
                </Button>
              </div>
            </Form.Item>

            <Form.Item
              label="密码"
              name="passwordHash"
              rules={[{ required: true, message: "请输入密码" }]}
            >
              <Input.Password placeholder="请输入密码" />
            </Form.Item>

            <Form.Item
              label="确认密码"
              name="passwordConfirmation"
              dependencies={['passwordHash']}
              rules={[
                { required: true, message: "请确认密码" },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('passwordHash') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('两次输入的密码不一致'));
                  },
                }),
              ]}
            >
              <Input.Password placeholder="请再次输入密码" />
            </Form.Item>

            <Button
              type="primary"
              htmlType="submit"
              loading={registering}
              className="register-btn"
            >
                注册
            </Button>
          </Form>
        </div>

        <div className="login-link">
            已有账号?
          <a
            onClick={() => {
              onClose(); 
              onLoginClick();
            }}
          >
            立即登录
          </a>
          </div>
      </div>
    </Modal>
  );
};

export default Register;